package top.jacktgq.web.servlet;
/**
 * @Author CandyWall
 * @Date 2021/6/20--12:33
 * @Description 处理学生信息的servlet
 */

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;
import top.jacktgq.pojo.Userinfo;
import top.jacktgq.utils.CandyMailUtils;
import top.jacktgq.utils.Email;
import top.jacktgq.utils.MapperUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;

@WebServlet(name = "UploadAttachmentAndSendEmailServlet", value = "/uploadAttachmentAndSendEmail")
public class UploadAttachmentAndSendEmailServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(1024 * 1024 * 4);// 文件上传缓存大小设定，单位为byte
        String tempPath = this.getServletContext().getRealPath("temp");// 磁盘缓存文件保存路径设定，这里设置为项目下temp文件夹绝对路径
        factory.setRepository(new File(tempPath));// 这两项设定也可以在构造函数中表现

        // 2创建阿帕奇文件上传核心类
        ServletFileUpload upload = new ServletFileUpload(factory);
        // 2.1判断form提交的是否是一个文件上传form
        if (ServletFileUpload.isMultipartContent(request)) {
            try {
                HashMap resultMap = new HashMap();
                String msg = "发送成功";
                Email email = new Email();
                String[] tos = null;
                // 2.2解析request为一个集合，元素为FileItem
                List<FileItem> parseRequest = upload.parseRequest(request);
                // 2.3设置解析到的文件名编码格式
                upload.setHeaderEncoding("UTF-8");
                // 2.4遍历解析集合，如果为文件，则
                for (FileItem fileItem : parseRequest) {
                    // 判断是否文件，结果为“true”就是普通表单，如果为“false”则是文件
                    if (fileItem.isFormField()) {
                        System.out.println(fileItem.getFieldName() + "-------" + fileItem.getString());
                        String fieldName = fileItem.getFieldName();
                        if (fieldName.equals("subject")) {
                            String subject = fileItem.getString();
                            subject = new String(subject.getBytes(StandardCharsets.ISO_8859_1), "utf-8");
                            email.setSubject(subject);
                        } else if (fieldName.equals("text")) {
                            String text = fileItem.getString();
                            text = new String(text.getBytes(StandardCharsets.ISO_8859_1), "utf-8");
                            email.setText(text);
                        } else if (fieldName.equals("tos")) {
                            String tosStr = fileItem.getString();
                            tos = tosStr.split(",");
                        }
                    } else {
                        String name = fileItem.getName();// 获取所上传文件的名称
                        InputStream in = fileItem.getInputStream();// 获得上传文件字节流
                        // BufferedInputStream bis = new BufferedInputStream(in);
                        // 创建输出文件
                        String outPath = this.getServletContext().getRealPath("temp/" + name);
                        File targetFile = new File(outPath);
                        FileOutputStream out = new FileOutputStream(targetFile);
                        // BufferedOutputStream bos = new BufferedOutputStream(out);
                        // 使用IOUtils工具输出， 也就是copy文件
                        IOUtils.copy(in, out);

                        // 文件上传完毕，清空缓存资料夹内容
                        in.close();
                        out.close();
                        fileItem.delete();

                        email.setAttachment_file(targetFile);
                    }
                }
                // 从session中获取管理员邮箱地址
                Userinfo userinfo = (Userinfo) request.getSession().getAttribute("userinfo");
                email.setFrom(userinfo.getEmail());
                email.setAuth_code(userinfo.getAuth_code());
                try {
                    // 群发邮件
                    sendEmails(email, tos);
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("插入数据失败！");
                    msg = "发送失败！";
                }
                resultMap.put("code", 0);
                resultMap.put("msg", msg);
                /*HashMap<String, Object> data = new HashMap<>();
                data.put("src", dirName + "/" + newName);
                resultMap.put("data", data);*/
                response.getWriter().write(MapperUtils.mapToJson(resultMap));
            } catch (FileUploadException e) {
                e.printStackTrace();
            }
        } else {
            // 如果不是文件上传类型，则采用普通表单获取方式
            System.out.println("不是文件上传表单！");
        }
//        Boolean ifSucceed = studentService.setCurriculumInfo(curriculumInfo);
//        response.getWriter().write("{\"ifSucceed\":"+ifSucceed+"}");
    }

    // 群发邮件
    private void sendEmails(Email email, String[] tos) {
        /*System.out.println(email);
        for(String to : tos) {
            System.out.print(to + " ");
        }
        System.out.println();*/
        for(String to : tos) {
            email.setTo(to);
            try {
                CandyMailUtils.sendEmail(email);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
